package com.glyxybxhtxt.controller.file;

import com.glyxybxhtxt.dataObject.Hc;
import com.glyxybxhtxt.response.ResponseData;
import com.glyxybxhtxt.service.BxdService;
import com.glyxybxhtxt.service.HcBatchService;
import com.glyxybxhtxt.service.HcService;
import com.glyxybxhtxt.util.DownloadFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @author Young Kbt
 * @date 2021/12/19 22:59
 * @description 处理批量添加耗材的文件
 */
@Slf4j
@RestController
public class HcBatch {
    @Autowired
    private HcBatchService hcBatchService;
    @Autowired
    private HcService hcService;
    @Autowired
    private BxdService bs;

    @RequestMapping(value = "/insertHcBatch", method = RequestMethod.POST)
    public ResponseData insertHcBatch(@RequestParam(value = "hcFile", required = false) MultipartFile hcFile) {
        // 获得文件名
        String name = hcFile.getOriginalFilename();
        // 后缀名
        String suffixName;
        if(name != null){
            suffixName = name.substring(name.indexOf("."));
        }else {
            return new ResponseData("文件名不能为空！");
        }
        if(!suffixName.equals(".xlsx")){
            return new ResponseData("文件格式错误");
        }
        try {
            List<Hc> hcDataList = this.excelToList(hcFile.getInputStream());
            if(hcDataList == null) {
                return new ResponseData("文件内容为空");
            }
            int i = hcService.insertHcBatch(hcDataList);
            if(i == 0) {
                return new ResponseData("上传失败！请重新上传，并关注耗材列表是否添加成功");
            }
            return new ResponseData("true","上传成功！请勿重复上传文件！", i);
        } catch (IOException e) {
            log.error("解析耗材文件错误:", e);
        }
        return new ResponseData("上传失败！");
    }
    
    @RequestMapping("/downloadHcTemplate")
    public String downloadHcTemplate(HttpServletResponse response) {
        String fileName = "hcAddTemplate.xlsx";     // 默认下载的文件名，根据业务需要替换成要下载的文件名
        InputStream fileInputStream = this.getClass().getResourceAsStream("/static/hcAddTemplate.xlsx");
        if (fileInputStream != null) {
            DownloadFile.DownloadExcelByIO(response, fileInputStream, fileName);
        }else {
            return "<h1 style='color: red; text-align: center'>文件不存在，请联系开发人员添加文件模板</h1>";
        }
        return "<h1 style='color: red; text-align: center'>下载成功，可关闭当前页面，请前往下载路径查看</h1>";
    }
    /**
     * 解析上传的文件内容
     * @param inputStream 文件 IO
     * @return 解析后，耗材数据的集合
     */
    public List<Hc> excelToList(InputStream inputStream) {
        return hcBatchService.excelToList(inputStream);
    }


}
